#!/bin/bash
cd "$(dirname "$0")/.."
source ./script/setup.sh

zip_uri='' # mandatory
cask_name='' # mandatory
build_version="0.0.0-SNAPSHOT"
while test $# -gt 0; do
    case $1 in
        --build-version) build_version="$2"; shift 2;;
        --zip-uri) zip_uri="$2"; shift 2;;
        --cask-name) cask_name="$2"; shift 2;;
        *) echo "Unknown arg $1"; exit 1;;
    esac
done

if test -z "$zip_uri"; then echo "--zip-uri is mandatory" > /dev/stderr; exit 1; fi
if test -z "$cask_name"; then echo "--cask-name is mandatory" > /dev/stderr; exit 1; fi

case "$cask_name" in
    aerospace) conflicts_with_casks="conflicts_with cask: 'aerospace-dev'";;
    aerospace-dev) conflicts_with_casks="conflicts_with cask: 'aerospace'";;
    *) echo "Unknown cask name: $cask_name. Allowed cask names: aerospace, aerospace-dev" > /dev/stderr; exit 1;;
esac

zip_file=''
if test -f "$zip_uri"; then
    zip_file=$zip_uri
    zip_uri="file://$(realpath "$zip_file")"
elif grep -q '^http' <<< "$zip_uri"; then
    zip_file=/tmp/AeroSpace-tmp.zip
    rm -rf $zip_file
    curl -L "$zip_uri" -o $zip_file
else
    echo "$zip_uri doesn't exist" > /dev/stderr; exit 1
fi
sha=$(shasum -a 256 "$zip_file" | awk '{print $1}')

cask_version=':latest' # Prevent 'Not upgrading aerospace, the latest version is already installed'
zip_root_dir="AeroSpace-v$build_version"
if ! grep -q SNAPSHOT <<< "$build_version"; then
    cask_version="'$build_version'"
    zip_root_dir=$(sed "s/$build_version/#{version}/g" <<< "$zip_root_dir")
    zip_uri=$(sed "s/$build_version/#{version}/g" <<< "$zip_uri")
fi

rm -f ".release/$cask_name.rb" || true
mkdir -p .release
cat > ".release/$cask_name.rb" <<EOF
cask "$cask_name" do # THE FILE IS GENERATED BY build-brew-cask.sh
  version $cask_version
  sha256 "$sha"

  url "$zip_uri"
  name "AeroSpace"
  desc "AeroSpace is an i3-like tiling window manager for macOS"
  homepage "https://github.com/nikitabobko/AeroSpace"
  $conflicts_with_casks

  depends_on macos: ">= :ventura" # macOS 13

  postflight do
    system "xattr -d com.apple.quarantine #{staged_path}/$zip_root_dir/bin/aerospace"
    system "xattr -d com.apple.quarantine #{appdir}/AeroSpace.app"
  end

  app "$zip_root_dir/AeroSpace.app"
  binary "$zip_root_dir/bin/aerospace"

  binary "$zip_root_dir/shell-completion/zsh/_aerospace",
      target: "#{HOMEBREW_PREFIX}/share/zsh/site-functions/_aerospace"
  binary "$zip_root_dir/shell-completion/bash/aerospace",
      target: "#{HOMEBREW_PREFIX}/etc/bash_completion.d/aerospace"
  binary "$zip_root_dir/shell-completion/fish/aerospace.fish",
      target: "#{HOMEBREW_PREFIX}/share/fish/vendor_completions.d/aerospace.fish"

  Dir["#{staged_path}/$zip_root_dir/manpage/*"].each { |man| manpage man }
end
EOF
